package com.lihan.GetSeatInLib.Service.impl;

import java.util.Date;

import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lihan.GetSeatInLib.Domain.User;
import com.lihan.GetSeatInLib.Exceptions.UnableJWTexception;
import com.lihan.GetSeatInLib.Service.JwtService;

@Service
public class JwtServiceImpl implements JwtService {

	//密文
	private static final String Secret = "GetSeats";
	
	private static final String issual = "lihan";
	
	//过期时间
	private static final Long EXPIRATIO = 400*3000L;
	
	//把加密的方法先摘出来
	private static Algorithm alg = Algorithm.HMAC256(Secret);
	
	@Override
	public String createTokenByUserName(User user) {
		
		Date now_time = new Date();
		//根据用户信息颁发token
		String token = JWT.create()
				.withIssuer(issual)
				.withClaim("username", user.getUserName())
				.withExpiresAt(new Date(now_time.getTime()+EXPIRATIO))
				.sign(alg);
		
		return token;
	}
	
	@Override
	public boolean verifierToken(String token, String username) {
		try {
			//根据加密的算法构造验证器
			JWTVerifier verifier = JWT.require(alg)
					.withIssuer(issual).withClaim("username", username)
					.build();
			
			//验证成功则返回true
			verifier.verify(token);
			return true;
		} catch (Exception e) {
			System.out.println("sdaeqw");
			 new UnableJWTexception(400,"jwt过期或无效");               
		}
		return false;
	}
}
